package com.gwm.cart.service;

import com.gwm.cart.entity.Cart;
import com.gwm.common.enums.ExceptionEnums;
import com.gwm.common.exceptions.LyException;
import com.gwm.common.threadlocals.UserHolder;
import com.gwm.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private String REFIX_KEY = "ly:cart:";

    public void addCart(Cart cart) {
        String skuId = cart.getSkuId().toString();
//        从ThreadLocal中获取用户id
        String userId = UserHolder.getUserId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(REFIX_KEY + userId);
//        原购物车中是否有此商品
        Boolean hasSku = hashOps.hasKey(skuId);
        if (hasSku) {
            String cartJsonString = hashOps.get(skuId);
            Cart cartRedis = JsonUtils.toBean(cartJsonString, Cart.class);
            cartRedis.setNum(cartRedis.getNum() + cart.getNum()); //重新计算数量
            hashOps.put(skuId, JsonUtils.toString(cartRedis));
        } else {  //即将添加的商品 在redis购物车中没有
            hashOps.put(skuId, JsonUtils.toString(cart));
        }


    }

//    public void cc(Cart cart) {
//        String userId = UserHolder.getUserId();
//        System.out.println("userId = " + userId);
//    }

    public List<Cart> queryCartList() {
//        从ThreadLocal中获取用户id
        String userId = UserHolder.getUserId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(REFIX_KEY + userId);
//        获取BoundHash中的所有value值
        List<String> cartListJsonString = hashOps.values();
        List<Cart> cartList = cartListJsonString.stream()
                .map(cartJsonString -> JsonUtils.toBean(cartJsonString, Cart.class))
                .collect(Collectors.toList());
        return cartList;
    }

    public void updateNum(Long skuId, Integer num) {
        // 获取当前用户
        String userId = UserHolder.getUserId();
        String key = REFIX_KEY + userId;

        // 获取hash操作的对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        String hashKey = skuId.toString();
        Boolean boo = hashOps.hasKey(hashKey);
        if (boo == null || !boo) {
            log.error("购物车商品不存在，用户：{}, 商品：{}", userId, skuId);
            throw new LyException(ExceptionEnums.CARTS_NOT_FOUND);
        }
        // 查询购物车商品
        Cart c = JsonUtils.toBean(hashOps.get(hashKey), Cart.class);
        // 修改数量
        c.setNum(num);

        // 写回redis
        hashOps.put(hashKey, JsonUtils.toString(c));
    }

    public void deleteCart(String skuId) {
        String userId = UserHolder.getUserId();
        // 获取登录用户
        String key = REFIX_KEY + userId;
        this.redisTemplate.opsForHash().delete(key, skuId);
    }

    private void addCartInRedis(Cart cart, BoundHashOperations<String, String, String> hashOps) {
        // 获取商品id，作为hashKey
        String hashKey = cart.getSkuId().toString();
        // 获取数量
        int num = cart.getNum();
        // 判断要添加的商品是否存在
        Boolean boo = hashOps.hasKey(hashKey);
        if (boo != null && boo) {
            // 存在，修改数量
            cart = JsonUtils.toBean(hashOps.get(hashKey), Cart.class);
            cart.setNum(num + cart.getNum());
        }
        // 写入redis
        hashOps.put(hashKey, JsonUtils.toString(cart));
    }

    public void addCartList(List<Cart> cartList) {
        // 获取当前用户
        String key = REFIX_KEY + UserHolder.getUserId();

        // 获取hash操作的对象，并绑定用户id
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        for (Cart cart : cartList) {
            addCartInRedis(cart, hashOps);
        }
    }
}
